package gw.com.android.ui.dialog;

import android.support.annotation.NonNull;
import android.view.View;

import com.gwtsz.gts2.hx.R;
import com.prolificinteractive.materialcalendarview.CalendarDay;
import com.prolificinteractive.materialcalendarview.MaterialCalendarView;
import com.prolificinteractive.materialcalendarview.OnDateSelectedListener;
import com.prolificinteractive.materialcalendarview.OnMonthChangedListener;

import java.util.Calendar;

public class CalendarPopView implements View.OnClickListener {

    private View mParent;
    private MaterialCalendarView mCvCalendar;
    private CalendarCallback mCallback;

    public CalendarPopView(View parent) {
        this.mParent = parent;

        mCvCalendar = (MaterialCalendarView) mParent.findViewById(R.id.calendarView);
        // 日期选择监听
        mCvCalendar.setOnDateChangedListener(new OnDateSelectedListener() {
            @Override
            public void onDateSelected(@NonNull MaterialCalendarView widget, @NonNull CalendarDay date, boolean selected) {
                if (selected) {
                    widget.setSelectedDate(date);
                    hide();
                    if (mCallback != null) {
                        mCallback.onSelectedDate(date.getCalendar());
                    }
                }
            }
        });

        // 月份可选择范围变更监听
        mCvCalendar.setOnMonthChangedListener(new OnMonthChangedListener() {
            @Override
            public void onMonthChanged(MaterialCalendarView widget, CalendarDay date) {
                if (mCallback == null) {
                    return;
                }

                if (isInMonth(Calendar.getInstance(), date.getCalendar())) {
                    mCallback.onCurDayVisibilityChanged(true);
                } else {
                    mCallback.onCurDayVisibilityChanged(false);
                }
            }
        });

    }


    @Override
    public void onClick(View v) {

    }

    public void setCallback(CalendarCallback callback) {
        this.mCallback = callback;
    }

    public void show(View parent, Calendar cur) {
        if (!isShowing()) {
            mParent.setVisibility(View.VISIBLE);
            //popWindow.showAsDropDown(parent, 0, 0);
            gotoCurrentDay(cur);
        }
    }

    public void gotoCurrentDay(Calendar calendar) {
        mCvCalendar.setCurrentDate(calendar);
        mCvCalendar.setSelectedDate(calendar);
    }


    public boolean isInMonth(Calendar cur, Calendar ref) {
        return cur.get(Calendar.MONTH) == ref.get(Calendar.MONTH);
    }


    public boolean isShowing() {
        return mParent.isShown();
    }

    public void hide() {
        mParent.setVisibility(View.GONE);
        if (mCallback != null) {
            mCallback.onDismiss();
        }
    }

    public interface CalendarCallback {

        void onSelectedDate(Calendar date);

        void onCurDayVisibilityChanged(boolean visible);

        void onDismiss();
    }

}
